package com.peaw.ccb.controller.annotation;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import test.java.poi.PoiTest;

@Controller
public class DianzihuidanController {
	
	private Logger log = LoggerFactory.getLogger(getClass());
	
	@RequestMapping("/F610302")
	public ModelAndView getF610302(@RequestParam("startDate")String startDate) {

		ModelAndView mv = new ModelAndView("F610302"); //电子对账明细账查询
		try {
			String xlsxDir = "D:/ccb/data/dianzihuidanchaxun/";
			String filename = startDate.substring(0,6) + ".xlsx";
			List<Map<String, String>> all = PoiTest.read2(xlsxDir + filename);
			mv.addObject("list", all);
		} catch (Exception e) {
			e.printStackTrace();
		}
		log.info(mv.toString());		
		return mv;
	
	}
	
	
	
	
	@RequestMapping("/F610302download")
	public void F610302download(HttpServletRequest request, HttpServletResponse response) {

		FileInputStream fos = null;  
	    ServletOutputStream sos = null;  
	    try{  
	    	
	        String fileName = request.getParameter("filename");
	        
	        String regex = "^[0-9A-Za-z]$";
	        StringBuffer namebuffer = new StringBuffer();
	        for (int i = 0; i < fileName.length(); i++) {
	        	String chartmp = fileName.charAt(i)+"";
	        	if ((chartmp).matches(regex)) {
	        		namebuffer.append(chartmp);
				}
			}
	        fileName = namebuffer.toString();
	        
	        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".pdf");  
	        response.setContentType("application/pdf");               
	        byte b[] = new byte[1024*1024*1];//1M  
	        int read = 0;  
	        fos = new FileInputStream(new File("D:/ccb/data/pdf/"+ fileName + ".pdf"));   
	        sos = response.getOutputStream();  
	        while((read=fos.read(b))!=-1){  
	            sos.write(b,0,read);//每次写1M  
	        }  
	        //OutputUtil.jsonOutPut(response, null);  
	    }catch (Exception e) { 
	    	e.printStackTrace();
	        throw new RuntimeException("");  
	    }finally{  
	        try {  
	            if(sos!=null){  
	                sos.close();  
	            }  
	            if(fos!=null){  
	                fos.close();  
	            }  
	        } catch (IOException e) {  
	        	e.printStackTrace();
	            throw new RuntimeException("");  
	        }  
	    }  
	}
	

}
